<?php defined('SYSPATH') or die('No direct script access.');

require_once Kohana::find_file('classes', 'util');

class Controller_Base extends Controller_Template 
{
	public $template; // see constructor

	protected $_isRpc = false;
	protected $_theme = 'bootstrap';
	
	/* Request context contains follwing information
	 * sessionInfo {userInfo, errorMessage, currentProjectSid}
	 * domainId
	 * domain
	 */
	protected $_requestContext; 
	protected $_sessionInfo; 

	protected $_profileHelper;
	protected $_projectHelper;
	protected $_resourceHelper;
	
	protected $domainService;

	public function __construct(Request $request, Response $response)
	{
		parent::__construct($request, $response);
		$this->template = $this->_theme.'/tpl_default';
		
		$dbgCntroller = $this->request->controller();
		$dbgAction = $this->request->action();
		
		// Load session
		$sessionInfo = new ArrayObject();
		$sessionInfo->userInfo = Util_Session::getUserInfo();
		$sessionInfo->errorMessage = Util_Session::get('error_message');
		$sessionInfo->currentProjectSid = (int)Util_Session::get(SNAME_PROJECT_SID);
		$this->_sessionInfo = $sessionInfo;
		
		$this->_requestContext = new stdClass();
		$this->_requestContext->sessionInfo = $sessionInfo;

		// Initialize reference to services
		$this->domainService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_DOMAIN.'/', ACCESS_TOKEN);
		$this->domainService->init($this->_requestContext);

		$this->_profileHelper = new Util_ProfileHelper($request, $this->_requestContext);
		$this->_projectHelper = new Util_ProjectHelper($request, $this->_requestContext);
		$this->_projectHelper->setProfileHelper($this->_profileHelper);
		$this->_resourceHelper = new Util_ResourceHelper($request, $this->_requestContext);
		
		// Load rest of information from services
		$this->_requestContext->domainId = $request->param('domain');
		$this->_requestContext->domainMember = NULL;
		if ($this->_sessionInfo->userInfo['userSid'] > 0) {
			$userSid = $this->_sessionInfo->userInfo['userSid'];
			
			$profile = $this->_profileHelper->getProfile($this->_sessionInfo->userInfo['userSid'], 9); // 1->tags + 8->relations
			$this->_requestContext->profile = $profile;
			$this->_requestContext->userInfo = $profile->creatorDto;
			
			if ($this->_requestContext->domainId == NULL) {
				$this->_requestContext->domainId = $this->_requestContext->userInfo->domainId;
			}
		}
		if ($this->_requestContext->domainId == NULL) {
			$this->_requestContext->domainId = 'host';
		}
		$this->_requestContext->domain = $this->domainService->getByXid($this->_requestContext->domainId);
		if ($this->_sessionInfo->userInfo['userSid'] > 0) {
			$domainMember = $this->domainService->getByXid('member/'.$this->_requestContext->domain->sid.'/'.$userSid);
			$this->_requestContext->domainMember = $domainMember;
		}

	}
	/**
	* The before() method is called before your controller action.
	* In our template controller we override this method so that we can
	* set up default values. These variables are then available to our
	* controllers if they need to be modified.
	*/
	public function before()
	{
		// If the user has not logged in (or has logged out) use plain (single column) layout
		if ($this->_sessionInfo->userInfo['userSid'] < 0) {
			if ( strcasecmp($this->request->controller(), 'Public') == 0 )
			{
				$this->template = $this->_theme.'/tpl_plain';
					
			} else if ( strcasecmp($this->request->controller(), 'Profile') == 0 )
			{
				// Allow profile view
				//$this->template = $this->_theme.'/tpl_plain';
			} else if ( strcasecmp($this->request->controller(), 'Domain') == 0 
					&& strcasecmp($this->request->action(), 'index') == 0) 
			{
				// Allow domain view
				//$this->template = $this->_theme.'/tpl_plain';
			} else {
				$redirTo = CONTROLLERPAGE.'/Public';	
				$this->request->redirect($redirTo);
			}
		}
		
		parent::before(); // loads the template
		
		// Sets the projectSid from the GET request or session (default)
		$projectSid = $this->request->query('projectSid');
		if ($projectSid == NULL)
			$projectSid = $this->_sessionInfo->currentProjectSid;
		$this->_requestContext->projectSid = $projectSid;
				
		if ($this->auto_render && !$this->_isRpc)
		{
			$this->template->set_global('_controller', $this->request->controller());
			$this->template->set_global('_action', $this->request->action());

			// Initialize empty values
			$this->template->title   = '';
			$this->template->content = '';
			
			$this->template->paneHeader = $this->createView('/pane_header');
			$this->template->paneFooter = $this->createView('/pane_footer');
				
			$this->template->styles = array();
			$this->template->scripts = array();	 
	
			$this->template->set_global("enableProjectNavBar", true);
			if ($this->_sessionInfo->userInfo['userSid'] > 0) {
				$this->_profileHelper->setProfileIntoTemplate($this->template, $this->_requestContext->profile);
			}
		}
	}
	 
	/**
	 * The after() method is called after your controller action.
	 * In our template controller we override this method so that we can
	 * make any last minute modifications to the template before anything
	 * is rendered.
	 */
	public function after()
	{
		if ($this->auto_render && !$this->_isRpc)
		{
			$styles = array(
				'public/css/seednia.css' => null
				//'public/css/screen.css' => 'screen, projection'
				//, 'public/css/print.css' => 'print'
				//, 'public/css/tagit.css'=> 'tags'
				, 'public/css/tagit-stylish-yellow.css'=> null
				, 'public/css/bootstrap-datepicker.css'=> null
				, 'public/jquery-ui/css/ui-lightness/jquery-ui-1.8.23.custom.css' => null
				, 'public/css/seednia.actionable.css' => null
			);
	
			$scripts = array(
				'public/js/jquery-1.8.0.min.js'
				, 'public/jquery-ui/js/jquery-ui-1.8.23.custom.min.js'
				, 'public/js/underscore-min.js'
				, 'public/js/backbone-min.js'
				, 'public/bootstrap2.1/js/bootstrap.js'
				//, 'public/bootstrap/js/bootstrap-dropdown.js'
				//, 'public/bootstrap/js/bootstrap-collapse.js'
				//, 'public/bootstrap/js/bootstrap-tab.js'
				, 'public/js/tagit.js'
			);
	
			$this->template->styles = array_merge( $styles, $this->template->styles );
			$this->template->scripts = array_merge( $scripts , $this->template->scripts );

			$this->template->set_global('requestContext', $this->_requestContext);
			$this->template->set_global('sessionInfo', $this->_sessionInfo);
			$this->template->set_global('util', $this);
			
			if ($this->_sessionInfo->userInfo['userSid'] > 0) {
				$this->_profileHelper->loadUnreadMessages($this->template);
				$this->_projectHelper->loadUserProjects($this->template);
				$this->_projectHelper->loadWaitingApproval($this->template);
			}
		}
		parent::after();
	}
	
	/**
	 * Creates a view using View factory
	 * @param type $viewName
	 * @return type 
	 */
	public function createView($viewName)
	{
		return View::factory($this->_theme.'/'.$viewName);
	}

	/**
	 * This fucntion
	 * @param type $paneRight empty produces default right pane which is <controllerName>_sbar_right
	 *				null means no right bar
	 * @return content view 
	 */
	public function index($title, $paneRight = '', $paneLeft = '')
	{
		return $this->loadViews($title, '_default_', $paneRight, $paneLeft);
	}
	
	/**
	 * Loads the left, content and right views.
	 * 
	 * @param type $title
	 * @param type $contentFrameName
	 * @param type $paneLeft
	 * @param type $paneRight
	 * @return type 
	 */
	public function loadViews($title, $contentFrameName='_default_', $paneRight = '', $paneLeft = '')
	{
		$this->template->title = __($title);
		
		$moduleName = strtolower($this->request->controller());
		if ($contentFrameName == '_default_') {
			$contentFrame = $this->createView('default_content_frame');
		} else if ($contentFrameName == '') {
			$contentFrame = $this->createView($moduleName.'_content_frame');
		} else {
			$contentFrame = $this->createView($contentFrameName);
		}
		$this->template->contentFrame = $contentFrame;
		
		if ($paneLeft === null) {
			$this->template->paneLeft = null;
		} else if ($paneLeft == '') {
			$this->template->paneLeft = $this->createView($moduleName.'_sbar_left');
		} else {
			$this->template->paneLeft = $this->createView($paneLeft);
		}
		
		/* Notice that the paneRight is in the content scope */
		if ($paneRight === null) {
			$contentFrame->paneRight = null;
		} else if ($paneRight == '') {
			$contentFrame->paneRight = $this->createView($moduleName.'_sbar_right');
		} else {
			$contentFrame->paneRight = $this->createView($paneRight);
		}
		
		return $contentFrame;
	}
	
	public function setTemplate($templateName)
	{
		$this->template = $this->_theme.$templateName;
	}
	
	public function isMethodGet()
	{
		return $this->request->method() == "GET";
	}
	
	public function isMethodPost()
	{
		return $this->request->method() == "POST";
	}
	
	public function setActiveProjectSid($activeProjectSid)
	{
		$this->_sessionInfo->currentProjectSid = Util_Session::set(SNAME_PROJECT_SID, (int)$activeProjectSid);
		return $this->_sessionInfo->currentProjectSid;
	}
	
		
	protected function getXid()
	{
		$xid = $this->request->param('xid');
		return $xid;
	}
} // End Controller_Base
